package com.xy.ssm.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xy.ssm.pojo.Emp;
import com.xy.ssm.pojo.Msg;
import com.xy.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2022/4/1 14:12
 * @description 处理员工crud
 */

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 获取员工数据
     *
     * @param pageNumber
     * @return
     */
    @GetMapping("/emp")
    @ResponseBody
    public Msg GetEmps(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
        // 引入pageHelper分页插件
        //查询之前调用pageHelper

        //传入页码和每页大小
        Page<Object> page = PageHelper.startPage(pageNumber, 10);

        //startPage后面紧跟的查询就是分页查询
        List<Emp> employees = employeeService.getAll();

        //使用pageInfo包装查询后的结果
        PageInfo pageInfo = new PageInfo(employees, 10);

        return Msg.success().add("pageInfo", pageInfo);

    }

    /**
     * 验证员工
     *
     * @param empName
     * @return
     */
    @GetMapping("/checkUser")
    @ResponseBody
    public Msg checkUser(String empName) {
        String regx = "(^[a-zA-Z0-9_-]{3,16}$)|(^[\u2E80-\u9FFF]{2,5})";
        if (!empName.matches(regx)) {
            Msg failure = Msg.failure();
            failure.setMsg("用户名必须是6-16位数字和字母的组合或者2-5位中文");
            return failure;
        }
        Boolean notExist = employeeService.checkUser(empName);
        if (notExist) {
            Msg success = Msg.success();
            success.setMsg("用户名可用");
            return success;
        }
        Msg failure = Msg.failure();
        failure.setMsg("用户名已存在");
        return failure;
    }

    /**
     * 员工保存
     *
     * @param emp
     * @return
     */
    @PostMapping("/emp")
    @ResponseBody
    public Msg saveEmp(@Valid Emp emp, BindingResult result) {
        System.out.println("post emp");
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.failure().add("errFields", map);
        } else {
            Msg msg = checkUser(emp.getEmpName());
            if (msg.getCode() == 400) {
                return msg;
            }
            Integer row = employeeService.saveEmp(emp);
            return Msg.success();
        }
    }

    /**
     * 通过id获取员工
     *
     * @param empId
     * @return
     */
    @GetMapping("emp/{empId}")
    @ResponseBody
    public Msg getEmpById(@PathVariable("empId") Integer empId) {
        Emp emp = employeeService.getEmpById(empId);
        return Msg.success().add("emp", emp);
    }

    /**
     * 通过id更新员工
     *
     * @param emp
     * @param result
     * @return
     */
    @PutMapping("emp/{empId}")
    @ResponseBody
    public Msg updateEmp(@Valid Emp emp, BindingResult result) {
        System.out.println("put " + emp);
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.failure().add("errFields", map);
        } else {
            Integer row = employeeService.updateEmp(emp);
            return Msg.success();
        }
    }


    /**
     * 批量删除和单个删除
     * @param ids
     * @return
     */
    @DeleteMapping("/emp/{ids}")
    @ResponseBody
    public Msg deleteEmpById(@PathVariable("ids") String ids) {
        //批量删除
        if (ids.contains(",")) {
            employeeService.deleteBatch(Arrays.asList(ids.split(",")));
        } else {//单个删除
            employeeService.deleteEmpById(Integer.parseInt(ids));
        }
        return Msg.success();
    }


}
